package me.sealer.java8.collector;

import me.sealer.java8.actparamterized.predicate.CustomPredicate;

import java.util.List;

/**
 * Created by sealer on 09-19-2017.
 */
public class NumberUtil {
    public static boolean isPrime(List<Integer> primes, int candidate) {
        return
//                primes.stream().filter(p -> p * p < candidate)//这种方式的缺点：如果质数和非质数的列表都非常大， 但filter 要处理整个流才能返回恰当的结果
                takeWhile(primes, p -> p * p > candidate).stream()//这种方式会在p^2>candidate时停止
                        .noneMatch(i -> candidate % i == 0);
    }

    private static <T> List<T> takeWhile(List<T> list, CustomPredicate<T> p) {
        int i = 0;
        for (T t : list) {
            if (p.test(t)) {
                return list.subList(0, i);
            }
            i++;
        }
        return list;
    }
}
